package com.wenkang.stu.controller;

import com.wenkang.stu.pojo.Account;
import com.wenkang.stu.service.AccountService;
import com.wenkang.stu.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping("account")
@RestController
public class AccountController {

    @Autowired
    private AccountService accountService;

    /**
     * @param data
     * @param type
     * @return
     */
    @GetMapping("register/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data, @PathVariable(value = "type") Integer type) {
        try {
            Boolean b = accountService.checkData(data, type);
            return ResponseEntity.ok(b);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    @PostMapping("register/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        accountService.sendVerifyCode(phone);
        // 发送验证码
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping("register")
    public ResponseEntity<Void> register(@RequestParam("account") Account account, @RequestParam("code") String code) {
        accountService.register(account, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 分页查询用户
     *
     * @return
     */
    @GetMapping
    public ResponseEntity<PageResult> selectAll(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "desc", defaultValue = "false") Boolean desc,
            @RequestParam(value = "sortBy", required = false) String[] sortBy,
            @RequestParam(value = "key", required = false) String[] key
    ) {
        PageResult<Account> pageResult = accountService.select(page, pageSize, desc, sortBy, key);
        return ResponseEntity.ok(pageResult);
    }

    @PostMapping
    public ResponseEntity<Void> insert(Account account) {
        accountService.insert(account);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping
    public ResponseEntity<Void> updateById(Account account) {
        accountService.updateById(account);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @DeleteMapping("{id}")
    public ResponseEntity<Void> deleteById(@PathVariable("id") String id) {
        accountService.deleteById(id);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
